package com.unlcn.ils.wms.backend.service.bigscreen.impl;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.unlcn.ils.wms.backend.bo.biBO.BiInOutDrayListBO;
import com.unlcn.ils.wms.backend.dto.bigscreenDTO.OutDrayChartDataDTO;
import com.unlcn.ils.wms.backend.enums.*;
import com.unlcn.ils.wms.backend.service.bigscreen.InOutDrayService;
import com.unlcn.ils.wms.backend.util.TimeUtil;
import com.unlcn.ils.wms.base.dto.BiInOutDrayDTO;
import com.unlcn.ils.wms.base.mapper.bigscreen.BiInOutDrayHeadMapper;
import com.unlcn.ils.wms.base.mapper.bigscreen.BiInOutDrayMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.BiInOutDrayExtMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.BiInOutDrayHeadExtMapper;
import com.unlcn.ils.wms.base.mapper.outbound.WmsDepartureRegisterMapper;
import com.unlcn.ils.wms.base.mapper.outbound.WmsPreparationPlanMapper;
import com.unlcn.ils.wms.base.mapper.sys.TmsCallHistoryMapper;
import com.unlcn.ils.wms.base.model.bigscreen.BiInOutDray;
import com.unlcn.ils.wms.base.model.bigscreen.BiInOutDrayHead;
import com.unlcn.ils.wms.base.model.outbound.WmsDepartureRegister;
import com.unlcn.ils.wms.base.model.outbound.WmsDepartureRegisterExample;
import com.unlcn.ils.wms.base.model.outbound.WmsPreparationPlan;
import com.unlcn.ils.wms.base.model.outbound.WmsPreparationPlanExample;
import com.unlcn.ils.wms.base.model.sys.TmsCallHistory;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lenovo on 2017/11/13.
 */
@Service
public class InOutDrayServiceImpl implements InOutDrayService {

    @Autowired
    private BiInOutDrayHeadExtMapper biInOutDrayHeadExtMapper;

    @Autowired
    private BiInOutDrayExtMapper biInOutDrayExtMapper;

    @Autowired
    private BiInOutDrayMapper biInOutDrayMapper;

    @Autowired
    private BiInOutDrayHeadMapper biInOutDrayHeadMapper;

    @Autowired
    private TmsCallHistoryMapper tmsCallHistoryMapper;

    @Autowired
    private WmsPreparationPlanMapper wmsPreparationPlanMapper;

    @Autowired
    private WmsDepartureRegisterMapper wmsDepartureRegisterMapper;

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;

    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;

    @Value("${tms.encode.key}")
    private String propertyKey;

    private Logger LOGGER = LoggerFactory.getLogger(InOutDrayServiceImpl.class);

    @Override
    public List<OutDrayChartDataDTO> inOutDrayChartCount() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        // 查询五天内最新的提车推移图统计数据
        List<BiInOutDrayHead> biInOutDrayHeadList = biInOutDrayHeadExtMapper.inOutDrayChartCount();

        OutDrayChartDataDTO outDrayChartDataDTO1 = new OutDrayChartDataDTO();
        OutDrayChartDataDTO outDrayChartDataDTO2 = new OutDrayChartDataDTO();
        OutDrayChartDataDTO outDrayChartDataDTO3 = new OutDrayChartDataDTO();
        OutDrayChartDataDTO outDrayChartDataDTO4 = new OutDrayChartDataDTO();

        outDrayChartDataDTO1.setName("进场板数");
        outDrayChartDataDTO2.setName("出场板数");
        outDrayChartDataDTO3.setName("进场及时率");
        outDrayChartDataDTO4.setName("出场及时率");

        Integer[] count1 = new Integer[5];
        Integer[] count2 = new Integer[5];
        Double[] rate1 = new Double[5];
        Double[] rate2 = new Double[5];

        String[] dates = TimeUtil.getBeforeDates1(5);
        for (int i = 0; dates.length > i; i++) {
            String date = dates[i];
            for (int num = 0; biInOutDrayHeadList.size() > num; num++) {
                BiInOutDrayHead biInOutDrayHead = biInOutDrayHeadList.get(num);
                if (format.format(biInOutDrayHead.getStatisticsTime()).contains(date)) {
                    count1[i] = biInOutDrayHead.getInboundNum();
                    count2[i] = biInOutDrayHead.getOutboundNum();
                    rate1[i] = biInOutDrayHead.getInboundRate();
                    rate2[i] = biInOutDrayHead.getOutboundRate();
                    break;
                }
            }
        }
        for (Integer num = 0; count1.length > num; num++) {
            Integer count = count1[num];
            if (count == null)
                count1[num] = 0;
        }
        for (Integer num = 0; count2.length > num; num++) {
            Integer count = count2[num];
            if (count == null)
                count2[num] = 0;
        }
        for (Integer num = 0; rate1.length > num; num++) {
            Double rate = rate1[num];
            if (rate == null)
                rate1[num] = 0.0;
        }
        for (Integer num = 0; rate2.length > num; num++) {
            Double rate = rate2[num];
            if (rate == null)
                rate2[num] = 0.0;
        }

        outDrayChartDataDTO1.setData(count1);
        outDrayChartDataDTO2.setData(count2);
        outDrayChartDataDTO3.setRate(rate1);
        outDrayChartDataDTO4.setRate(rate2);

        outDrayChartDataDTO1.setDate(TimeUtil.getBeforeDates2(5));
        outDrayChartDataDTO2.setDate(TimeUtil.getBeforeDates2(5));
        outDrayChartDataDTO3.setDate(TimeUtil.getBeforeDates2(5));
        outDrayChartDataDTO4.setDate(TimeUtil.getBeforeDates2(5));

        List<OutDrayChartDataDTO> outDrayChartDataDTOList = new ArrayList<OutDrayChartDataDTO>();
        outDrayChartDataDTOList.add(outDrayChartDataDTO1);
        outDrayChartDataDTOList.add(outDrayChartDataDTO2);
        outDrayChartDataDTOList.add(outDrayChartDataDTO3);
        outDrayChartDataDTOList.add(outDrayChartDataDTO4);

        return outDrayChartDataDTOList;
    }

    @Override
    public List<BiInOutDray> inOutDrayLineCount() {
        return biInOutDrayExtMapper.inOutDrayLineCount();
    }


    /**
     * 获取大屏板车进出场数据--展示
     * <p>2017-12-19 新需求:指令号D开头不显示，显示前10条数据，表格里加上实际进场时间，实际出场时间</p>
     *
     * @return 返回值
     * @throws Exception 异常表现层处理
     * @author hs
     */
    @Override
    public ArrayList<BiInOutDrayDTO> inOutDrayLineCountNew() throws Exception {
        LOGGER.info("InOutDrayServiceImpl.inOutDrayLineCountNew param : {}");
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("start", 0);
        paramMap.put("end", 10);
        paramMap.put("orderBy", " wiod.id desc");
        List<BiInOutDray> biInOutDrays = biInOutDrayExtMapper.selectInOutDrayLineByParam(paramMap);
        ArrayList<BiInOutDrayDTO> lists = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(biInOutDrays)) {
            biInOutDrays.forEach((BiInOutDray v) -> {
                BiInOutDrayDTO biInOutDrayDTO = new BiInOutDrayDTO();
                BeanUtils.copyProperties(v, biInOutDrayDTO);
                //WmsDepartureRegisterExample example = new WmsDepartureRegisterExample();
                //example.setOrderByClause("dr_id desc");
                //example.setLimitStart(0);
                //example.setLimitEnd(1);
                //example.createCriteria().andDrVehiclePlateLike("%" + v.getVehicleCard())
                //        .andDispatchNoEqualTo(v.getDispatchNo())
                //        .andInOutTypeEqualTo(WmsGateControllerTypeEnum.GATE_IN.getCode());
                //List<WmsDepartureRegister> gateIn = wmsDepartureRegisterMapper.selectByExample(example);
                //if (CollectionUtils.isNotEmpty(gateIn)) {
                //    biInOutDrayDTO.setGateInTime(gateIn.get(0).getDrDepartureTime());
                //}
                //WmsDepartureRegisterExample exampleOut = new WmsDepartureRegisterExample();
                //exampleOut.setOrderByClause("dr_id desc");
                //exampleOut.setLimitStart(0);
                //exampleOut.setLimitEnd(1);
                //exampleOut.createCriteria().andDrVehiclePlateLike("%" + v.getVehicleCard())
                //        .andDispatchNoEqualTo(v.getDispatchNo())
                //        .andInOutTypeEqualTo(WmsGateControllerTypeEnum.GATE_OUT.getCode());
                //List<WmsDepartureRegister> gateOut = wmsDepartureRegisterMapper.selectByExample(exampleOut);
                //if (CollectionUtils.isNotEmpty(gateOut)) {
                //    biInOutDrayDTO.setGateOutTime(gateOut.get(0).getDrDepartureTime());
                //}
                biInOutDrayDTO.setGateInTime(v.getInBoundTime());//该数据取值为数据库对应字段  其字段的值以计算板车出入场状态的逻辑进行区分
                biInOutDrayDTO.setGateOutTime(v.getShipTime());
                lists.add(biInOutDrayDTO);
            });
        }
        return lists;
    }

    private String getInOutDrayList(TmsCallHistory tmsCallHistory) {

        String result = null;

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String dateStr = format.format(calendar.getTime());

        String strUrl = propertyUrl + TmsUrlEnum.BI_INOUTDRAYLIST.getText();
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);

        map.put("date", dateStr);

        try {
            tmsCallHistory.setTmsUrl(strUrl);
            tmsCallHistory.setPullOrPush(0);
            tmsCallHistory.setCallStartTime(new Date());
            tmsCallHistory.setTmsUrlType(TmsUrlTypeEnum.BI_INOUTDRAYLIST.getValue());
            tmsCallHistory.setParameters(dateStr);
            result = HttpRequestUtil.sendHttpPost(strUrl, headerMap, map, time);

        } catch (Exception e) {
            LOGGER.error("InOutDrayServiceImpl.addDrayChart error : ", e);
            throw new BusinessException("访问tms接口失败");
        }

        return result;
    }

    @Override
    public void addDrayChart() {

        TmsCallHistory tmsCallHistory = new TmsCallHistory();
        String result = getInOutDrayList(tmsCallHistory);

        try {
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");

                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);

                if (!success) {
                    LOGGER.error("InOutDrayServiceImpl callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }

                List<BiInOutDrayListBO> tmsBOList = JSONArray.parseArray(records, BiInOutDrayListBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());

                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

                Map<String, Integer> inmap = Maps.newHashMap();
                Map<String, Integer> intimemap = Maps.newHashMap();
                Map<String, Integer> outmap = Maps.newHashMap();
                Map<String, Integer> outtimemap = Maps.newHashMap();

                for (int i = 0; i < 5; i++) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - i);
                    Date beforeFiveDate = calendar.getTime();
                    BiInOutDrayHead biInOutDrayHead = new BiInOutDrayHead();
                    biInOutDrayHead.setVersion(dateStr2);
                    biInOutDrayHead.setStatisticsTime(beforeFiveDate);
                    biInOutDrayHead.setCreateTime(new Date());
                    biInOutDrayHeadMapper.insertSelective(biInOutDrayHead);
                    String dateStr = format1.format(beforeFiveDate);
                    inmap.put(dateStr, 0);
                    outmap.put(dateStr, 0);
                    intimemap.put(dateStr, 0);
                    outtimemap.put(dateStr, 0);
                }

                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");

                tmsBOList.forEach((BiInOutDrayListBO v) -> {

                    Date come_Date = null;
                    Date out_Date = null;
                    String strComeDate = null;
                    String strOutDate = null;

                    //更新
                    if (!Strings.isNullOrEmpty(v.getCome_date())) {
                        try {
                            come_Date = sdf.parse(v.getCome_date());
                            strComeDate = format1.format(come_Date);
                            if (inmap.get(strComeDate) != null) {
                                int intCount = inmap.get(strComeDate) + 1;
                                inmap.put(strComeDate, intCount);
                            }
                        } catch (ParseException e) {
                            LOGGER.error("InOutDrayServiceImpl.addDrayChart error : ", e);
                            throw new BusinessException("日期转换异常!");
                        }
                    }

                    if (!Strings.isNullOrEmpty(v.getOut_date())) {
                        try {
                            out_Date = sdf.parse(v.getOut_date());
                            strOutDate = format1.format(out_Date);
                            if (outmap.get(strOutDate) != null) {
                                int outCount = outmap.get(strOutDate) + 1;
                                outmap.put(strOutDate, outCount);
                            }
                        } catch (ParseException e) {
                            LOGGER.error("InOutDrayServiceImpl.addDrayChart error : ", e);
                            throw new BusinessException("日期转换异常!");
                        }
                    }

                    WmsPreparationPlanExample example = new WmsPreparationPlanExample();
                    example.createCriteria().andPpGroupDispNoEqualTo(v.getShipno()).andPpWhCodeEqualTo(WhCodeEnum.UNLCN_XN_CQ.getValue());

                    List<WmsPreparationPlan> preparationPlanList = wmsPreparationPlanMapper.selectByExample(example);

                    if (CollectionUtils.isNotEmpty(preparationPlanList)) {
                        WmsPreparationPlan preparationPlan = preparationPlanList.get(0);
                        Date ppEstimateLoadingTime = preparationPlan.getPpEstimateLoadingTime();
                        Date ppEstimateFinishTime = preparationPlan.getPpEstimateFinishTime();

                        if (!Strings.isNullOrEmpty(v.getCome_date()) &&
                                ppEstimateLoadingTime.getTime() >= come_Date.getTime()) {
                            //bugfix 2017-12-18 修复空指针异常
                            if (intimemap.get(strComeDate) != null) {
                                int inCount = intimemap.get(strComeDate) + 1;
                                intimemap.put(strComeDate, inCount);
                            }
                        }

                        if (!Strings.isNullOrEmpty(v.getOut_date()) &&
                                ppEstimateFinishTime.getTime() >= out_Date.getTime()) {
                            if (outtimemap.get(strOutDate) != null) {
                                int outCount = outtimemap.get(strOutDate) + 1;
                                outtimemap.put(strOutDate, outCount);
                            }
                        }
                    }


                });

                //计算出入及时率
                for (Map.Entry<String, Integer> entry : inmap.entrySet()) {
                    Map<String, Object> alParamMap = Maps.newHashMap();
                    alParamMap.put("inboundNum", entry.getValue());
                    alParamMap.put("statisticsTime", entry.getKey());
                    alParamMap.put("version", dateStr2);
                    if (intimemap.containsKey(entry.getKey())) {
                        Integer inttime = intimemap.get(entry.getKey());
                        if (entry.getValue() != 0 && entry.getValue() != null) {
                            //bugfix 2017-12-18 修复出入库及时率显示0%
                            float inrate = (float) inttime / (float) entry.getValue();
                            float inrate_format = (float) Math.round(inrate * 100) / 100;
                            alParamMap.put("inboundRate", inrate_format);
                        }
                        if (Objects.equals(alParamMap.get("inboundRate"), null)) {
                            alParamMap.put("inboundRate", 0.0f);
                        }
                    }
                    biInOutDrayHeadExtMapper.updateByStatVersion(alParamMap);
                }

                for (Map.Entry<String, Integer> entry : outmap.entrySet()) {
                    Map<String, Object> alParamMap = Maps.newHashMap();
                    alParamMap.put("outboundNum", entry.getValue());
                    alParamMap.put("statisticsTime", entry.getKey());
                    alParamMap.put("version", dateStr2);
                    if (outtimemap.containsKey(entry.getKey())) {
                        Integer ottime = outtimemap.get(entry.getKey());
                        if (entry.getValue() != 0 && entry.getValue() != null) {
                            float otrate = (float) ottime / (float) entry.getValue();
                            float otrate_format = (float) Math.round(otrate * 100) / 100;
                            alParamMap.put("outboundRate", otrate_format);
                        }
                        if (Objects.equals(alParamMap.get("outboundRate"), null)) {
                            alParamMap.put("outboundRate", 0.0f);
                        }

                    }
                    biInOutDrayHeadExtMapper.updateByStatVersion(alParamMap);
                }


            }

        } catch (Exception e) {
            LOGGER.error("InOutDrayServiceImpl.addDrayChart error : ", e);
            throw new BusinessException("保存失败");
        }
    }

    /**
     * 本方法用于保存大屏报表展示的进出场列表数据
     *
     * @descrption 设置板车进出场的状态  计算的时间是  wms预计备料开始完成时间 和 tms系统的板车指令入场时间和指令板车出场时间比较
     */
    @Override
    public void addDrayLineInfo() {

        TmsCallHistory tmsCallHistory = new TmsCallHistory();
        String result = getInOutDrayList(tmsCallHistory);

        try {
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");

                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);

                if (!success) {
                    LOGGER.error("addDrayLineInfo callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }

                List<BiInOutDrayListBO> tmsBOList = JSONArray.parseArray(records, BiInOutDrayListBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());

                tmsBOList.forEach((BiInOutDrayListBO v) -> {
                    //新增
                    BiInOutDray biInOutDray = new BiInOutDray();

                    biInOutDray.setDispatchNo(v.getShipno());
                    biInOutDray.setVehicleCard(v.getVehicle());
                    biInOutDray.setCarrierName(v.getSupplier());
                    biInOutDray.setDirverName(v.getDriver());
                    biInOutDray.setPhone(v.getMobile());

                    //根据调度指令查询备料计划
                    WmsPreparationPlanExample example = new WmsPreparationPlanExample();
                    example.setOrderByClause("pp_id desc");
                    example.setLimitStart(0);
                    example.setLimitEnd(1);
                    example.createCriteria().andIsDeletedEqualTo(DeleteFlagEnum.NORMAL.getValue()).andPpGroupDispNoEqualTo(v.getShipno()).andPpWhCodeEqualTo(WhCodeEnum.UNLCN_XN_CQ.getValue());

                    List<WmsPreparationPlan> preparationPlanList = wmsPreparationPlanMapper.selectByExample(example);
                    if (CollectionUtils.isNotEmpty(preparationPlanList)) {
                        WmsPreparationPlan preparationPlan = preparationPlanList.get(0);
                        Date ppEstimateLoadingTime = preparationPlan.getPpEstimateLoadingTime();
                        Date ppEstimateFinishTime = preparationPlan.getPpEstimateFinishTime();
                        biInOutDray.setPlanInTime(ppEstimateLoadingTime);
                        biInOutDray.setPlanOutTime(ppEstimateFinishTime);
                        Date date = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");
                        Date come_Date = null;
                        Date out_date = null;

                        try {
                            if (StringUtils.isNotBlank(v.getCome_date())) {
                                come_Date = sdf.parse(v.getCome_date());
                                biInOutDray.setInBoundTime(come_Date);//以tms的指令板车入场时间作为实际入场时间
                            }
                            if (StringUtils.isNotBlank(v.getOut_date())) {
                                out_date = sdf.parse(v.getOut_date());
                                biInOutDray.setShipTime(out_date);
                            }
                        } catch (ParseException e) {
                            LOGGER.error("PickDataServiceImpl.addPickData error : ", e);
                            throw new BusinessException("日期转换异常!");
                        }

                        //未进场：erp系统未入场（但当前时间没有超过新wms计划装车时间）
                        if (ppEstimateLoadingTime.getTime() >= date.getTime()) {
                            biInOutDray.setStatus(InOutDrayStatusEnum.NOT_APPROACH.getValue());
                        }

                        //超期未进场：erp系统未入场（已超过新wms计划装车时间）
                        if (ppEstimateLoadingTime.getTime() < date.getTime() && Strings.isNullOrEmpty(v.getCome_date())) {
                            biInOutDray.setStatus(InOutDrayStatusEnum.EXTENDED_NOT_APPROACH.getValue());
                        }

                        //正常进场：erp系统已入场（入场时间没有超过新wms计划装车时间）
                        if (come_Date != null && come_Date.getTime() <= ppEstimateLoadingTime.getTime()
                                && Strings.isNullOrEmpty(v.getOut_date())) {
                            biInOutDray.setStatus(InOutDrayStatusEnum.NORMAL_APPROACH.getValue());
                        }

                        //超期进场：erp系统已入场（但入场时间超过新wms计划装车时间）
                        if (come_Date != null && come_Date.getTime() > ppEstimateLoadingTime.getTime()
                                && Strings.isNullOrEmpty(v.getOut_date())) {
                            biInOutDray.setStatus(InOutDrayStatusEnum.EXTENDED_APPROACH.getValue());
                        }

                        //正常离场：erp系统已发运（发运时间没有超过新wms计划装车完成时间）
                        if (out_date != null && out_date.getTime() <= ppEstimateFinishTime.getTime()) {
                            biInOutDray.setStatus(InOutDrayStatusEnum.NORMAL_DEPARTURE.getValue());
                        }

                        //超期未离场：erp系统未发运（当前时间超过新wms计划装车完成时间）
                        if (out_date != null && out_date.getTime() > ppEstimateFinishTime.getTime()) {
                            biInOutDray.setStatus(InOutDrayStatusEnum.EXTENDE_NOT_DEPARTURE.getValue());
                        }
                        //时间都为空
                        if (out_date == null && come_Date == null) {
                            biInOutDray.setStatus(InOutDrayStatusEnum.NOT_APPROACH.getValue());
                        }

                    } else {
                        biInOutDray.setStatus(InOutDrayStatusEnum.NOT_APPROACH.getValue());
                    }

                    biInOutDray.setVersion(dateStr2);

                    biInOutDrayMapper.insertSelective(biInOutDray);

                });
            }

        } catch (Exception e) {
            LOGGER.error("InOutDrayServiceImpl.addDrayChart error : ", e);
            throw new BusinessException("保存失败");
        }
    }


    /**
     * 本方法用于保存大屏报表展示的进出场列表数据
     * 更新需求:更新状态的时间依据以wms系统的出入场闸门开启时间比较保存状态
     *
     * @descrption 设置板车进出场的状态  计算的时间是  wms预计备料开始完成时间 和 wms系统的出入场指令闸门开启时间记录比较
     */
    @Override
    public void addDrayLineInfoNew() {
        LOGGER.info("InOutDrayServiceImpl.addDrayLineInfoNew param:{}");
        TmsCallHistory tmsCallHistory = new TmsCallHistory();
        String result = getInOutDrayList(tmsCallHistory);
        try {
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");

                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);

                if (!success) {
                    LOGGER.error("addDrayLineInfoNew callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }

                List<BiInOutDrayListBO> tmsBOList = JSONArray.parseArray(records, BiInOutDrayListBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());

                tmsBOList.forEach((BiInOutDrayListBO v) -> {
                    //新增
                    BiInOutDray biInOutDray = new BiInOutDray();

                    biInOutDray.setDispatchNo(v.getShipno());
                    biInOutDray.setVehicleCard(v.getVehicle());
                    biInOutDray.setCarrierName(v.getSupplier());
                    biInOutDray.setDirverName(v.getDriver());
                    biInOutDray.setPhone(v.getMobile());

                    //根据闸门实际出入场开启的时间判断对应指令车辆的状态
                    WmsDepartureRegisterExample example = new WmsDepartureRegisterExample();
                    example.setOrderByClause("dr_id desc");
                    example.setLimitStart(0);
                    example.setLimitEnd(1);
                    example.createCriteria().andDrVehiclePlateLike("%" + v.getVehicle())
                            .andDispatchNoEqualTo(v.getShipno())
                            .andInOutTypeEqualTo(WmsGateControllerTypeEnum.GATE_IN.getCode());
                    List<WmsDepartureRegister> gateIn = wmsDepartureRegisterMapper.selectByExample(example);
                    Date come_Date = null;
                    if (CollectionUtils.isNotEmpty(gateIn)) {
                        come_Date = gateIn.get(0).getDrDepartureTime();
                    }

                    //根据调度指令查询备料计划
                    WmsPreparationPlanExample planExample = new WmsPreparationPlanExample();
                    planExample.setOrderByClause("pp_id desc");
                    planExample.setLimitStart(0);
                    planExample.setLimitEnd(1);
                    planExample.createCriteria().andIsDeletedEqualTo(DeleteFlagEnum.NORMAL.getValue()).andPpGroupDispNoEqualTo(v.getShipno()).andPpWhCodeEqualTo(WhCodeEnum.UNLCN_XN_CQ.getValue());
                    List<WmsPreparationPlan> preparationPlanList = wmsPreparationPlanMapper.selectByExample(planExample);

                    if (CollectionUtils.isNotEmpty(preparationPlanList)) {
                        WmsPreparationPlan preparationPlan = preparationPlanList.get(0);
                        Date ppEstimateLoadingTime = preparationPlan.getPpEstimateLoadingTime();
                        Date ppEstimateFinishTime = preparationPlan.getPpEstimateFinishTime();
                        biInOutDray.setPlanInTime(ppEstimateLoadingTime);
                        biInOutDray.setPlanOutTime(ppEstimateFinishTime);
                        Date date = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");

                        WmsDepartureRegisterExample exampleOut = new WmsDepartureRegisterExample();
                        exampleOut.setOrderByClause("dr_id desc");
                        exampleOut.setLimitStart(0);
                        exampleOut.setLimitEnd(1);
                        exampleOut.createCriteria().andDrVehiclePlateLike("%" + v.getVehicle())
                                .andDispatchNoEqualTo(v.getShipno())
                                .andInOutTypeEqualTo(WmsGateControllerTypeEnum.GATE_OUT.getCode());
                        List<WmsDepartureRegister> gateOut = wmsDepartureRegisterMapper.selectByExample(exampleOut);
                        Date out_date = null;
                        if (CollectionUtils.isNotEmpty(gateOut)) {
                            out_date = gateOut.get(0).getDrDepartureTime();
                        }
                        biInOutDray.setInBoundTime(come_Date);//以wms的闸门开启时间作为实际入场和出场时间
                        biInOutDray.setShipTime(out_date);//以wms的闸门开启时间作为实际入场和出场时间
                        //1、未进场： 当天无实际进场时间记录
                        //2、超期未进场：计划进场时间＜实际进场时间
                        //3、正常进场：实际进场时间＜计划进场时间
                        //4、超期进场：实际进场时间＞计划进场时间
                        //5、正常离场：计划离场时间＞实际出场时间
                        //6、超期未离场：计划离场时间＜实际出场时间
                        //未进场：erp系统未入场（但当前时间没有超过新wms计划装车时间）
                        if (out_date == null && ppEstimateLoadingTime != null) {
                            //进场状态
                            if (ppEstimateLoadingTime.getTime() >= date.getTime()) {
                                biInOutDray.setStatus(InOutDrayStatusEnum.NOT_APPROACH.getValue());
                            }

                            //超期未进场：erp系统未入场（已超过新wms计划装车时间）
                            if (ppEstimateLoadingTime.getTime() < date.getTime() && Objects.equals(come_Date, null)) {
                                biInOutDray.setStatus(InOutDrayStatusEnum.EXTENDED_NOT_APPROACH.getValue());
                            }

                            //正常进场：erp系统已入场（入场时间没有超过新wms计划装车时间）
                            if (come_Date != null && come_Date.getTime() <= ppEstimateLoadingTime.getTime()) {
                                biInOutDray.setStatus(InOutDrayStatusEnum.NORMAL_APPROACH.getValue());
                            }

                            //超期进场：erp系统已入场（但入场时间超过新wms计划装车时间）
                            if (come_Date != null && come_Date.getTime() > ppEstimateLoadingTime.getTime()) {
                                biInOutDray.setStatus(InOutDrayStatusEnum.EXTENDED_APPROACH.getValue());
                            }

                        } else if (out_date != null && ppEstimateFinishTime != null) {
                            //出场状态
                            //正常离场：erp系统已发运（发运时间没有超过新wms计划装车完成时间）
                            if (out_date.getTime() <= ppEstimateFinishTime.getTime()) {
                                biInOutDray.setStatus(InOutDrayStatusEnum.NORMAL_DEPARTURE.getValue());
                            }

                            //超期未离场：计划离场时间＜实际出场时间
                            if (ppEstimateFinishTime.getTime() < out_date.getTime()) {
                                biInOutDray.setStatus(InOutDrayStatusEnum.EXTENDE_NOT_DEPARTURE.getValue());
                            }
                        } else {
                            biInOutDray.setStatus(InOutDrayStatusEnum.NOT_APPROACH.getValue());
                        }
                    } else {
                        biInOutDray.setStatus(InOutDrayStatusEnum.NOT_APPROACH.getValue());
                    }
                    biInOutDray.setVersion(dateStr2);

                    biInOutDrayMapper.insertSelective(biInOutDray);

                });
            }

        } catch (Exception e) {
            LOGGER.error("InOutDrayServiceImpl.addDrayChart error : ", e);
            throw new BusinessException("保存失败");
        }
    }


}
